package com.contract.spirit.ui.login

import androidx.activity.viewModels
import androidx.appcompat.app.AppCompatActivity
import cn.woochen.comlib.util.ConfigPref
import cn.woochen.comlib.util.UserPref
import com.contract.commonlib.http.ext.parseState
import com.contract.commonlib.config.Constants
import com.contract.spirit.ui.UserViewModel
import com.contract.spirit.ui.exchange.ExchangeBindListActivity
import com.contract.spirit.ui.main.MainActivity

/**
 * @author: witness
 * created: 2021/9/22
 * desc:
 */
object LoginManger {
    private var mToken by UserPref(Constants.USER_TOKEN, "")
    private var phone by ConfigPref(Constants.USER_PHONE, "")

    fun registerLoginObervable(loginViewModel: LoginViewModel, activity: AppCompatActivity) {
        loginViewModel.loginObservable.observe(activity, { it ->
            parseState(it, {
                mToken = it
                phone = loginViewModel.phoneNumber.get().toString()
                onLoginSuccess(activity)
            })
        })
    }

    private fun onLoginSuccess(activity: AppCompatActivity) {
        val mUserViewModel by activity.viewModels<UserViewModel>()
        mUserViewModel.exchangeResponse.observe(activity,{ it ->
            parseState(it,{
                if (it.hasNoBindExchange()){
                    ExchangeBindListActivity.launch(activity)
                }else{
                    MainActivity.launch(activity)
                }
                activity.finish()
            })
        })
        mUserViewModel.getExchangeList()
    }
}